const express = require("express");
const router = express.Router();

const config = require("../../config/config");
const ArticleModel = require("../../model/articleModel");
const ArticleCateModel = require("../../model/articleCateModel");
const { multer, getUnix } = require("../../model/tools");

router.get("/", async (req, res) => {
    let page = req.query.page || 1;
    let pageSize = 10;
    let json = {};
    const keywords = req.query.keywords;
    if(keywords) {
        json = Object.assign(json, { title: { $regex: new RegExp(keywords) } });
    }
    // const result = await ArticleModel.find({}).skip((page - 1) * pageSize).limit(pageSize);
    let result = await ArticleModel.aggregate([{
        $lookup: {
            from: "article_cate",
            localField: "cid",
            foreignField: "_id",
            as: "cate"
        }
    }, {
        $match: json
    }, {
        $sort: { add_time: -1 }
    }, {
        $skip: (page - 1) * pageSize
    }, {
        $limit: pageSize
    }]);
    let count = await ArticleModel.countDocuments(json);
    res.render("admin/article/index.html", {
        list: result,
        totalPages: Math.ceil(count/pageSize),
        page: page,
        keywords
     });
})

router.get("/add", async (req, res) => {
    let result = await ArticleCateModel.aggregate([{
        $lookup: {
            from: "article_cate",
            localField: "_id",
            foreignField: "pid",
            as: "items"
        }
    }, {
        $match: { pid:"0" }
    }]);
    res.render("admin/article/add.html", { articleCate: result });
})

router.post("/doAdd", multer().single("article_img") ,async (req, res) => {
    const imgStr = req.file ? req.file.path.substring(7) : "";
    const result = new ArticleModel(Object.assign(req.body, { article_img: imgStr, add_time: getUnix() }))
    await result.save();
    res.redirect(`/${config.adminPath}/article`);
})

router.get("/edit", async (req, res) => {
    // 获取要修改的数据
    const id = req.query.id;
    const ArcitleResult = await ArticleModel.find({ "_id": id });

    // 获取分类信息
    let cateResult = await ArticleCateModel.aggregate([{
        $lookup: {
            from: "article_cate",
            localField: "_id",
            foreignField: "pid",
            as: "items"
        }
    }, {
        $match: { pid:"0" }
    }]);
    res.render("admin/article/edit.html", { list: ArcitleResult[0], articleCate: cateResult });
})

router.post("/doEdit", multer().single("article_img") , async (req, res) => {
    try {
        if(req.file) {
            const imgStr = req.file ? req.file.path.substring(7) : "";
            await ArticleModel.updateOne({_id: req.body.id }, Object.assign(req.body, { article_img: imgStr }));
        } else {
            await ArticleModel.updateOne({_id: req.body.id }, req.body);
        }
        res.redirect(`/${config.adminPath}/article`);
    } catch (error) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${config.adminPath}/article/edit?id=${req.body.id}`,
            "message": "修改数据失败"
        });
    }
})

router.get("/delete", async (req, res) => {
    var id = req.query.id;
    await ArticleModel.deleteOne({ _id: id });
    res.render("admin/public/success.html", {
        "redirectUrl": `/${req.app.locals.adminPath}/article`,
        "message": "删除数据成功"
    })
})

// 富文本上传图片并返回链接
router.post("/doUploadImage", multer().single("file") ,async (req, res) => {
    const imgStr = req.file ? req.file.path.substring(7) : "";
    // {link: 'path/to/image.jpg'}
    res.send({ link: `/${imgStr}` });
})

module.exports = router